package com.lenovo.smarttraffic.zm;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.DriveStep;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.TMC;
import com.amap.api.services.route.WalkRouteResult;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class OffMapActivity extends BaseActivity implements RouteSearch.OnRouteSearchListener, Serializable {
    private List<LatLonPoint> throughPointList;
    protected List<Polyline> allPolyLines = new ArrayList<Polyline>();
    private AMap aMap;
    private PolylineOptions mPolylineOptions;
    private List<Marker> throughPointMarkerList = new ArrayList<Marker>();
    protected List<Marker> stationMarkers = new ArrayList<Marker>();
    private List<LatLng> mLatLngsOfPath;
    private List<TMC> tmcs;
    private MapView mapView;
    protected LatLng startPoint;
    protected LatLng endPoint;
    private String[] split;
    String TAG = "离线地图==Test ";
    String url = "http://192.168.1.110:8088/transportservice/action/GetRouteInfo.do";
    private Spinner sp1;
    private Spinner sp2;
    private ArrayList<AddressBean> carParkList;
    private Marker carParkMarker;
    private Marker markerEnd;
    private Marker markerStart;

    private DriveRouteResult mDriveRouteResult;
    private LatLng positionStart;
    private LatLng positionEnd;
    private LatLonPoint mStartPoint;
    private LatLonPoint mEndPoint;
    private DrivePath drivePath;
    protected Marker startMarker;
    protected Marker endMarker;


    private RouteSearch mRouteSearch;

    private TextView detailsRoute;

    private List<MyRoute> myRoutes;

    private String startPlacel;
    private String endPlacel;
    float Distance = 0;
    float Duration = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState); // 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        initView();


    }

    private void okhttp(String origin, String destination) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("UserName", "user1");
            jsonObject.put(origin, destination);
            OkHttpUtils1.doRequest(url, jsonObject.toString(), new OkHttpUtils1.OnResLis() {
                @Override
                public void success(String result) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_off_map;
    }


    private void addMarkersToMap() {
        LatLng latLng = new LatLng(Double.valueOf(split[0]), Double.valueOf(split[1]));
        BitmapDescriptor bitmap0 = BitmapDescriptorFactory.fromResource(R.mipmap.p);
        MarkerOptions markerOption = new MarkerOptions().icon(bitmap0)
                .position(latLng).visible(true);
        carParkMarker = aMap.addMarker(markerOption);
    }

    private void initView() {
        carParkList = new ArrayList<>();
        initList();

        //上一个活动中的任务
        Intent intent = getIntent();
        String strlatLng = intent.getStringExtra("latLng");
        String parkName = intent.getStringExtra("parkName");
        split = strlatLng.split(",");
        initToolBar(findViewById(R.id.toolbar), true, "离线地图");

        sp1 = (Spinner) findViewById(R.id.sp1);
        sp2 = (Spinner) findViewById(R.id.sp2);
        detailsRoute = findViewById(R.id.detailsRoute);
        detailsRoute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent(OffMapActivity.this, DetailsRouteActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("DetailsRoute", (Serializable) myRoutes);
                if (myRoutes != null) {
                    intent1.putExtras(bundle);
                    intent1.putExtra("time",Duration);
                    intent1.putExtra("distance",Distance);
                    startActivity(intent1);
                } else {
                    Toast.makeText(OffMapActivity.this, "未规划线路", Toast.LENGTH_SHORT).show();
                }


            }
        });
        sp1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {//选择item的选择点击监听事件
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                // 将所选mySpinner 的值带入myTextView 中
                clearMarker(markerStart);
                startPlacel = carParkList.get(arg2).getName();
                driveRouteStart(carParkList.get(arg2));
                drive();
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        sp2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                clearMarker(markerEnd);
                endPlacel = carParkList.get(i).getName();
                driveRouteEnd(carParkList.get(i));
                drive();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        addMarkersToMap();// 往地图上添加marker
    }

    private void initList() {
        carParkList.add(new AddressBean("", null, null));
        carParkList.add(new AddressBean("天安门", 39.908689, 116.397475));
        carParkList.add(new AddressBean("联想大厦", 40.042737, 116.309884));
        carParkList.add(new AddressBean("西铁营桥", 39.860512, 116.347593));
        carParkList.add(new AddressBean("G107", 39.802303, 116.209749));
        carParkList.add(new AddressBean("G2路段", 39.847603, 116.472871));
        carParkList.add(new AddressBean(" 联想总部园区", 40.046307, 116.272103));
        carParkList.add(new AddressBean(" 首都机场", 40.080525, 116.603039));
        carParkList.add(new AddressBean("北京西站", 39.894911, 116.322056));
        carParkList.add(new AddressBean("联想总部园区", 40.046307, 116.273117));
        carParkList.add(new AddressBean("北京南站", 39.865195, 116.378545));
    }


    private void clearMarker(Marker m) {
        if (aMap != null) {
            if (m != null) {
                m.destroy();
            }
        }
    }


    private void driveRouteStart(AddressBean bean) {
        if (bean.getName().equals("")) {
        } else {
            //为导航做准备
            mStartPoint = new LatLonPoint(bean.longitude, bean.latitude);
            LatLng latLng = new LatLng(bean.longitude, bean.latitude);
            BitmapDescriptor bitmap0 = BitmapDescriptorFactory.fromResource(R.mipmap.start);
            MarkerOptions markerOption = new MarkerOptions().icon(bitmap0)
                    .position(latLng)
                    .draggable(false);
            markerStart = aMap.addMarker(markerOption);
        }
    }

    private void driveRouteEnd(AddressBean bean) {
        if (bean.getName().equals("")) {
        } else {
            //为导航做准备
            mEndPoint = new LatLonPoint(bean.longitude, bean.latitude);

            LatLng latLng = new LatLng(bean.longitude, bean.latitude);
            BitmapDescriptor bitmap0 = BitmapDescriptorFactory.fromResource(R.mipmap.end);
            MarkerOptions markerOption = new MarkerOptions().icon(bitmap0)
                    .position(latLng)
                    .draggable(false);
            markerEnd = aMap.addMarker(markerOption);
        }
    }

    public void drive() {
        if (aMap != null) {
            if (markerStart != null) {
                carParkMarker.destroy();
                if (markerEnd != null) {
                    positionStart = markerStart.getPosition();
                    positionEnd = markerEnd.getPosition();
                    if (positionStart.equals(positionEnd)) {
                        Toast.makeText(this, "不能相同", Toast.LENGTH_SHORT).show();
                        sp2.setSelection(0, true);
                    } else {
                        mRouteSearch = new RouteSearch(this);
                        searchRouteResult(2, RouteSearch.DrivingDefault);
                        mRouteSearch.setRouteSearchListener(this);
                    }
                } else {
                    Toast.makeText(this, "终点不能为空", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "起点不能为空", Toast.LENGTH_SHORT).show();
            }
            okhttp("", "");
        }
    }

    public void searchRouteResult(int routeType, int mode) {

        if (positionStart == null) {
            return;
        }
        if (positionEnd == null) {
        }

        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint, mEndPoint);
        if (routeType == 2) {// 驾车路径规划
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, null,
                    null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
        }
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        aMap.clear();
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mDriveRouteResult = result;
                    drivePath = mDriveRouteResult.getPaths().get(0);
                    if (drivePath == null) {
                        Log.e(TAG, "onDriveRouteSearched: " + null);
                        return;
                    }
                    addToMap();
                } else if (result != null && result.getPaths() == null) {
                    Toast.makeText(this, "对不起，没有搜索到相关数据！", Toast.LENGTH_SHORT).show();
                }

            } else {
                Toast.makeText(this, "对不起，没有搜索到相关数据！", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "对不起，没有搜索到相关数据！", Toast.LENGTH_SHORT).show();
        }


    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }


    private void initPolylineOptions() {
        mPolylineOptions = null;
        mPolylineOptions = new PolylineOptions();
        mPolylineOptions.color(Color.parseColor("#537edc")).width(25);
    }

    public void addToMap() {
        initPolylineOptions();
        try {
            if (aMap == null) {
                return;
            }

            mLatLngsOfPath = new ArrayList<LatLng>();
            tmcs = new ArrayList<TMC>();


            List<DriveStep> drivePaths = drivePath.getSteps();

            initDetailsRoute(drivePaths);//与地图无关   与下一个活动有关
//            for (int i = 0; i < drivePaths.size() - 1; i++) {
//                Log.e(TAG, "getTollDistance " + drivePaths.get(1).getTollDistance());
//                Log.e(TAG, "getAction: " + drivePaths.get(1).getAction());
//                Log.e(TAG, "getAssistantAction: " + drivePaths.get(1).getAssistantAction());
//                Log.e(TAG, "getOrientation: " + drivePaths.get(1).getOrientation());
//                Log.e(TAG, "getTollRoad: " + drivePaths.get(1).getTollRoad());
//                Log.e(TAG, "getDistance: " + drivePaths.get(1).getDistance());
//                Log.e(TAG, "getDuration: " + drivePaths.get(1).getDuration());
//                Log.e(TAG, "getRouteSearchCityList: " + drivePaths.get(1).getRouteSearchCityList());
//                Log.e(TAG, "getPolyline: " + drivePaths.get(1).getPolyline());
//                Log.e(TAG, "getTolls: " + drivePaths.get(1).getTolls());
//                Log.e(TAG, "getTMCs: " + drivePaths.get(1).getTMCs());
//                Log.e(TAG, "getRoad: " + drivePaths.get(1).getRoad());
//                Log.e(TAG, "getInstruction: " + drivePaths.get(1).getInstruction());
//
//            }

            for (DriveStep step : drivePaths) {
                List<LatLonPoint> latlonPoints = step.getPolyline();
                List<TMC> tmclist = step.getTMCs();
                tmcs.addAll(tmclist);
                addDrivingStationMarkers(step, convertToLatLng(latlonPoints.get(0)));
                for (LatLonPoint latlonpoint : latlonPoints) {
                    mPolylineOptions.add(convertToLatLng(latlonpoint));
                    mLatLngsOfPath.add(convertToLatLng(latlonpoint));
                }

            }
            if (startMarker != null) {
                startMarker.remove();
                startMarker = null;
            }
            if (endMarker != null) {
                endMarker.remove();
                endMarker = null;
            }
            addStartAndEndMarker();
            //addThroughPointMarker();
            showPolyline();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private void initDetailsRoute(List<DriveStep> drivePaths) {
        myRoutes = new ArrayList<>();
        myRoutes.add(new MyRoute("", startPlacel, ""));
        for (int j = 0; j < drivePaths.size() - 1; j++) {
            // getDistance: 229.0
            //     getDuration: 58.0

            myRoutes.add(new MyRoute(drivePaths.get(j).getAssistantAction(), drivePaths.get(j).getRoad(), drivePaths.get(j).getInstruction()));
            Distance += drivePaths.get(j).getDistance();
            Duration += drivePaths.get(j).getDuration();
        }
        myRoutes.add(new MyRoute("", endPlacel, ""));

    }


    public LatLng convertToLatLng(LatLonPoint point) {
        return new LatLng(point.getLatitude(), point.getLongitude());
    }

    private void addDrivingStationMarkers(DriveStep driveStep, LatLng latLng) {

        addStationMarker(new MarkerOptions()
                .position(latLng)
                .title("\u65B9\u5411:" + driveStep.getAction()
                        + "\n\u9053\u8DEF:" + driveStep.getRoad())
                .snippet(driveStep.getInstruction()).visible(false)
                .anchor(0.5f, 0.5f).icon(null));
    }

    protected void addStationMarker(MarkerOptions options) {
        if (options == null) {
            return;
        }
        Marker marker = aMap.addMarker(options);
        if (marker != null) {
            stationMarkers.add(marker);
        }

    }

    protected void addStartAndEndMarker() {

        startPoint = convertToLatLng(mDriveRouteResult.getStartPos());
        endPoint = convertToLatLng(mDriveRouteResult.getTargetPos());
        if (startPoint == null) {
            Toast.makeText(this, "meizhi", Toast.LENGTH_SHORT).show();
        }
        startMarker = aMap.addMarker((new MarkerOptions())
                .position(startPoint).icon(BitmapDescriptorFactory.fromResource(R.mipmap.start))
                .title("\u8D77\u70B9").visible(true));

        endMarker = aMap.addMarker((new MarkerOptions())
                .position(endPoint).icon(BitmapDescriptorFactory.fromResource(R.mipmap.end))
                .title("\u7EC8\u70B9").visible(true));
    }

//    private void addThroughPointMarker() {
//        if (this.throughPointList != null && this.throughPointList.size() > 0) {
//            LatLonPoint latLonPoint = null;
//            for (int i = 0; i < this.throughPointList.size(); i++) {
//                latLonPoint = this.throughPointList.get(i);
//                if (latLonPoint != null) {
//                    throughPointMarkerList.add(aMap
//                            .addMarker((new MarkerOptions())
//                                    .position(
//                                            new LatLng(latLonPoint
//                                                    .getLatitude(), latLonPoint
//                                                    .getLongitude()))
//                                    .visible(true)
//                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.down))
//                                    .title("\u9014\u7ECF\u70B9")));
//                }
//            }
//        }
//    }

    private void showPolyline() {
        addPolyLine(mPolylineOptions);
    }

    protected void addPolyLine(PolylineOptions options) {
        if (options == null) {
            return;
        }
        Polyline polyline = aMap.addPolyline(options);
        if (polyline != null) {
            allPolyLines.add(polyline);
        }
    }


}
